<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ChatRoom</title>
    <style>
        #app {
            width: 400px;
            margin: 50px auto 0;
        }
        .form {
            margin: 10px auto;
        }
        #app input {
            width: 300px;
            height: 20px;
            float: right;
        }
        #app label {
            height: 26px;
            line-height: 26px;
        }

        textarea {
            width: 400px;
        }
    </style>
</head>
<body>

<div id="app">
    <div class="form"><label for="from">从用户</label><input type="text" id="from" value="zhangsan"/></div>
    <div class="form"><label for="to">到用户</label><input type="text" id="to" value="wangwu"/></div>
    <div class="form"><label for="roomId">当前房间</label><input type="text" id="roomId" value="1000Room"/></div>
    <div><label for="text"></label><textarea id="text" cols="30" rows="10"></textarea></div>
    <button onclick="connect()">链接服务端</button>
    <button onclick="send()">发送到用户</button>
    <button onclick="joinRoom()">加入房间</button>
    <button onclick="sendRoom()">发送到房间</button>
    <button onclick="leaveRoom()">离开房间</button>
    <button onclick="disConnect()">断开服务端</button>
    <div id="content">
    </div>
</div>
<script>
    // LOGIN 登录事件
    const LOGIN = "login"
    // LOGOUT 注销事件
    const LOGOUT = "logout"
    // JOINTAG 加入标签(分组)
    const JOINTAG = "joinTag"
    // LEAVETAG 离开标签(房间)
    const LEAVETAG = "leaveTag"
    // CHAT 聊天事件
    const CHAT = "chat"
    // PING 事件
    const PING = "ping"
    // PONG 事件
    const PONG = "PONG"
    let ws=null
    let interval=null
    let content = document.getElementById("content");
    function connect() {
        disConnect()
        let from = document.getElementById("from").value;
        // 1.发送链接并握手
        ws = new WebSocket(`ws://127.0.0.1/socket?clientId=${from}`);
        ws.onopen = function (event){
            console.log("打开链接消息接收");
            // 2.链接已经打开则发送用户注册
            let from = document.getElementById("from").value;
            ws.send(JSON.stringify({event: LOGIN,data: {userId: from}}))
        }
        ws.onclose = function (event) {
            console.log("关闭链接消息接收",event?.reason);
            // 3.发送用户注销功能
            ws=null
        }
        ws.onerror = function (event) {
            console.log("链接错误消息接收:",event);
            // 4.发送用户注销功能
            ws=null
        }

        ws.onmessage = function (event){
            console.log("消息接收:data=",event.data);
            // console.log("接收到数据lastEventId=",event.lastEventId);
            // console.log("接收到数据origin=",event.origin);
            // console.log("接收到数据ports=",event.ports);
            // console.log("接收到数据source=",event.source);
            let msg=JSON.parse(event.data)
            if (msg.event===CHAT) {
                let element=document.createElement("p")
                element.innerText=msg.data.userId+"说:" + msg.data.content
                content.appendChild(element)
            }
        }
        //每隔60秒发送一次心跳
        interval = setInterval(function () {
            if(ws && ws.readyState===ws.OPEN){
                ws.send(JSON.stringify({event:"ping"}));
            } else {
                clearInterval(interval)
            }
        }, 60 * 1000)
    }
    function send() {
        if(ws && ws.readyState===ws.OPEN) {
            let to = document.getElementById("to").value;
            let text = document.getElementById("text").value;
            ws.send(JSON.stringify({event: CHAT, data: { content: text, userId: to}}));
            console.log("发送消息给用户")

            let element=document.createElement("p")
            element.innerText="我说:"+ text
            content.appendChild(element)
        }
    }
    function disConnect(){
        if(ws && ws.readyState===ws.OPEN){
            ws.close(1000,"客户端主动关闭")
            console.log("发送主动关闭连接")
            if (interval) {
                clearInterval(interval)
            }
            ws=null
            interval=null
        }
    }
    function joinRoom(){
        if(ws && ws.readyState===ws.OPEN) {
            let roomId = document.getElementById("roomId").value;
            ws.send(JSON.stringify({event: JOINTAG, data: { tag:roomId}}));
            console.log("加入房间消息")
        }
    }
    function leaveRoom(){
        if(ws && ws.readyState===ws.OPEN) {
            let roomId = document.getElementById("roomId").value;
            ws.send(JSON.stringify({event: LEAVETAG, data: { tag:roomId}}));
            console.log("离开房间消息")
        }
    }
    function sendRoom(){
        if(ws && ws.readyState===ws.OPEN) {
            let text = document.getElementById("text").value;
            let roomId = document.getElementById("roomId").value;
            ws.send(JSON.stringify({event: CHAT, data: {content: text, tag:roomId}}));
            console.log("发送到房间消息")
        }
    }
</script>

</body>
</html>
